package com.easylinkin.linkappapi.project.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.mechanical.entity.EquipmentLocation;
import com.easylinkin.linkappapi.project.entity.ProjectPoint;
import com.easylinkin.linkappapi.project.service.IProjectPointService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;


/**
 * 工点信息表
 *
 * @author xy
 * @since 2025-06-10
 */
@Api(tags = "工点信息表")
@RestController
@RequestMapping("/project/projectPoint")
public class ProjectPointController {
    @Autowired
    private IProjectPointService projectPointService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    /**
     * 分页列表查询
     *
     * @param requestModel
     * @return
     */
    @ApiOperation(value="分页列表查询", notes="分页列表查询")
    @PostMapping(value = "/listPage")
    public RestMessage queryPageList(@RequestBody RequestModel<ProjectPoint> requestModel) {
        // Assert.notNull(requestModel,"参数不能为空");
        // Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        if(CollUtil.isNotEmpty(requestModel.getSorts())){
            requestModel.getSorts().forEach(s -> {
                requestModel.getPage().getOrders().add(new OrderItem().setColumn(StrUtil.toUnderlineCase(s.getField())).setAsc("ASC".equalsIgnoreCase(s.getSortRule())));
            });
        }else{
            requestModel.getPage().getOrders().add(new OrderItem().setColumn("create_time_").setAsc(false));
        }
        if (null == requestModel.getCustomQueryParams()){
            ProjectPoint projectPoint = new ProjectPoint();
            requestModel.setCustomQueryParams(projectPoint);
        }
        requestModel.getCustomQueryParams().setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        IPage<ProjectPoint> pageList = projectPointService.page(requestModel.getPage(), Wrappers.lambdaQuery(requestModel.getCustomQueryParams()));
        return RestBuilders.successBuilder().data(pageList).build();
    }

    /**
     * 保存
     *
     * @param projectPoint
     * @return
     */
    @ApiOperation(value="保存", notes="保存")
    @PostMapping(value = "/save")
    public RestMessage save(@RequestBody ProjectPoint projectPoint) {
        // 工点名称唯一校验
        Assert.notNull(projectPoint,"参数不能为空");
        Assert.hasLength(projectPoint.getPointName(),"工点名称不能为空");
        QueryWrapper<ProjectPoint> queryWrapper = Wrappers.query();
        queryWrapper.eq("point_name_", projectPoint.getPointName());
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        queryWrapper.eq("tenant_id_", tenantId);
        if (StrUtil.isNotEmpty(projectPoint.getId())) {
            queryWrapper.ne("id", projectPoint.getId());
        }
        int points = projectPointService.count(queryWrapper);
        if(points > 0) {
            return RestBuilders.errorBuilder().message("工点名称已存在").build();
        }
        setBase(projectPoint);
        if(StrUtil.isNotEmpty(projectPoint.getId())){
            projectPointService.updateById(projectPoint);
        } else{
            projectPointService.save(projectPoint);
        }
        return RestBuilders.successBuilder().message("保存成功" ).build();
    }

    /**
     * 设置基本属性
     *
     * @param projectPoint
     */
    private void setBase(ProjectPoint projectPoint) {
        projectPoint.setModifyTime(new Date());
        projectPoint.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (StringUtils.isBlank(projectPoint.getId())) {
            projectPoint.setCreateId(linkappUserContextProducer.getCurrent().getId());
            projectPoint.setCreateTime(new Date());
            projectPoint.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id删除", notes="通过id删除")
    @DeleteMapping(value = "/delete")
    public RestMessage delete(@RequestParam("id") String id) {
        projectPointService.removeById(id);
        return RestBuilders.successBuilder().message("删除成功").build();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value="批量删除", notes="批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public RestMessage deleteBatch(@RequestParam("ids") String ids) {
        this.projectPointService.removeByIds(Arrays.asList(ids.split(",")));
        return RestBuilders.successBuilder().message("批量删除成功").build();
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id查询", notes="通过id查询")
    @GetMapping(value = "/queryById")
    public RestMessage queryById(@RequestParam("id") String id) {
        ProjectPoint projectPoint = projectPointService.getById(id);
        if(projectPoint == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
        return RestBuilders.successBuilder().data(projectPoint).build();
    }
}
